package spring.angularjs.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import spring.angularjs.domain.Reporttransaction;
import spring.angularjs.domain.Transaction;
import spring.angularjs.domain.User;
import spring.angularjs.domain.json.TransactionJson;
import spring.angularjs.services.Services;

@Controller
@RequestMapping(value = "/transaction")
public class TransactionController {

	@Autowired
	private Services services;

	@RequestMapping(value = "/start")
	public String goPartialTransaction() {
		return "transaction";
	}

	@RequestMapping(value = "/getList", method = RequestMethod.GET, headers = "Accept=application/json")
	@ResponseBody
	public List<TransactionJson> getListTransaction() {
		List<Transaction> list = services.getListTransactionNotReport();
		List<TransactionJson> listJson = new ArrayList<TransactionJson>();
		for (int i = 0; i < list.size(); i++) {
			Transaction t = list.get(i);
			TransactionJson tj = new TransactionJson(t.getIdtransaction(), t
					.getStatustransaction().getNamestatus(), t
					.getAccountByIdAccountReceive().getIdaccount(), t
					.getAccountByIdAccountSent().getIdaccount(),
					t.getIdCustomerSent(), t.getIsCustomerReceive(),
					t.getDatetransaction(), t.getAmount(), t.getStatusreport());
			listJson.add(tj);
		}
		return listJson;
	}
	
	@RequestMapping(value="/update/{id}", method=RequestMethod.POST, headers="Accept=application/json")
	@ResponseBody
	public void uploadStatusReport(@PathVariable("id") String id){
		Transaction tr = services.getTransacionById(id);
		tr.setStatusreport("yes");
		services.updateTransaction(tr);
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String iduser = auth.getName();
		User user = services.getUserAuthentication(iduser);
		Reporttransaction rtt = new Reporttransaction(user, tr);
		services.addReportTransaction(rtt);
	}
}
